package com.ge.med.cchelper.util;

import java.awt.Container;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.io.InputStream;

import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;

import org.eclipse.core.resources.IProject;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;

import com.ge.med.cchelper.bean.CSession;
import com.ge.med.cchelper.bean.Host;
import com.ge.med.cchelper.bean.Response;
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.UIKeyboardInteractive;
import com.jcraft.jsch.UserInfo;

public class SSLhelper {
	private Session session;
	private String viewName;
	private String cleartool;

	public SSLhelper(CSession csession) {
		session = csession.getHostSession();
		if (session == null) {
			try {
				JSch jsch = new JSch();
				Host host = csession.getHost();
				LogUtil.out("[SESSION]create session from " + host.getIp()+ " with " + host.getUserid());
				session = jsch.getSession(host.getUserid(), host.getIp(), 22);
				MyUserInfo ui = new MyUserInfo(host.getPassword());
				session.setUserInfo(ui);
				session.connect();
				csession.setHostSession(session);

			} catch (JSchException e) {
				LogUtil.err("[SESSION][STATUS]:" + e.getMessage());
			}
		}
		
		viewName = csession.getViewName();
		cleartool = csession.getCleartool();
	}

	public String getCleartool() {
		return cleartool;
	}

	public void dispose() {
		session.disconnect();
	}

	/**
	 * 
	 * @param cmd
	 * @return
	 */
	public Response executeCT(String cmd) {
		String newcmd = cleartool + " setview -exec \" " + cmd + "  \" "
				+ viewName + "";
		return execute(newcmd);
	}

	/**
	 * 
	 * @param files
	 * @return
	 */
	public Response executeCheckout(String comments, String... files) {
		String objectFiles = "";
		for (String file : files) {
			objectFiles = objectFiles + " " + file;
		}
		String newcmd = "";
		if (comments != null) {
			newcmd = cleartool + " co -c " + comments + " " + objectFiles;
		} else {
			newcmd = cleartool + " co -nc " + objectFiles;
		}
		return executeCT(newcmd);
	}

	/**
	 * 
	 * @param files
	 * @return
	 */
	public Response executeUNCheckout(String... files) {
		String objectFiles = "";
		for (String file : files) {
			objectFiles = objectFiles + " " + file;
		}
		String newcmd = cleartool + " unco -rm " + objectFiles;

		return executeCT(newcmd);
	}

	/**
	 * 
	 * @param comments
	 * @param files
	 * @return
	 */
	public Response executeCheckin(String comments, String... files) {
		String objectFiles = "";
		for (String file : files) {
			objectFiles = objectFiles + " " + file;
		}
		String newcmd = "";
		if (comments != null) {
			newcmd = cleartool + " ci -c " + comments + " " + objectFiles;
		} else {
			newcmd = cleartool + " ci -nc " + objectFiles;
		}
		return executeCT(newcmd);
	}

	/**
	 * execute a shell command
	 * 
	 * @param cmd
	 * @return
	 */
	public Response execute(String cmd) {
		LogUtil.out("[COMMAND]:" + cmd);
		Response res = new Response();
		try {
			Channel channel = session.openChannel("exec");
			ChannelExec channelExc = (ChannelExec) channel;
			channelExc.setCommand(cmd);
			channel.setInputStream(null);
			((ChannelExec) channel).setErrStream(LogUtil.err());
			InputStream in = channel.getInputStream();
			channel.connect();

			byte[] tmp = new byte[1024];
			StringBuilder text = new StringBuilder();
			while (true) {
				while (in.available() > 0) {
					int i = in.read(tmp, 0, 1024);
					if (i < 0)
						break;
					text.append(new String(tmp, 0, i));
				}
				if (channel.isClosed()) {
					break;
				}
			}
			// System.out.println(text);
			res.setContent(text);
			LogUtil.host("[RETURN]:" + channel.getExitStatus() + "\r\n" + text);
			res.setStatus(channel.getExitStatus());
			channel.disconnect();
		} catch (Exception e) {
			// e.printStackTrace();
			LogUtil.err("[RETURN]:" + e.getMessage());
		}
		return res;
	}
	

	public int testConnect() throws Exception {
		int flag = -1;
		try {
			Channel channel = session.openChannel("exec");
			ChannelExec channelExc = (ChannelExec) channel;
			channelExc.setCommand("uname -a");
			channel.setInputStream(null);
			((ChannelExec) channel).setErrStream(System.err);
			InputStream in = channel.getInputStream();
			channel.connect();
			byte[] tmp = new byte[1024];
			StringBuilder text = new StringBuilder();
			while (true) {
				while (in.available() > 0) {
					int i = in.read(tmp, 0, 1024);
					if (i < 0)
						break;
					text.append(new String(tmp, 0, i));
				}
				if (channel.isClosed()) {
					break;
				}
			}
			flag = channel.getExitStatus();
			LogUtil.out(flag + " " + text);
			channel.disconnect();
		} catch (Exception e) {
			// e.printStackTrace();
			throw new Exception(e.getMessage());
		}
		return flag;
	}

	public static void main(String[] str) {
		CSession session = new CSession();
		Host host = new Host();
		host.setIp("3.87.209.36");
		host.setUserid("fz027939");
		host.setPassword("change1");
		session.setHost(host);
		session.setViewName("sles_hde.54_chenxp");
		session.setVobRoot("/vobs/");
		session.setCleartool("/usr/atria/bin/cleartool");
		SSLhelper helper = new SSLhelper(session);
		try {
			int res = helper.testConnect();
			if (res == 0) {
				System.out.println("login done!");
				
				Response res0 = helper.executeCT("/usr/atria/bin/cleartool lsco -cview -me -avobs -sho");
									//lsco -cview
					String lsContent = res0.getContent().toString().trim();
					String reallsContent = StringHelper.matchVobsPwd(lsContent);
					System.out.println("return:"+reallsContent);

				
				
			}else{
				System.out.println("login failing!");
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public static class MyUserInfo implements UserInfo, UIKeyboardInteractive {
		public MyUserInfo(String passwd) {
			this.passwd = passwd;
		}

		public String getPassword() {
			return passwd;
		}

		public boolean promptYesNo(String str) {
//			Object[] options = { "yes", "no" };
//
//			int foo = JOptionPane.showOptionDialog(null, str, "Warning",
//					JOptionPane.DEFAULT_OPTION, JOptionPane.WARNING_MESSAGE,
//					null, options, options[0]);
//
//			return foo == 0;
			return true;
		}

		String passwd;

		public String getPassphrase() {
			return null;
		}

		public boolean promptPassphrase(String message) {
			return true;
		}

		public boolean promptPassword(String message) {
			return true;
		}

		public void showMessage(String message) {
			//JOptionPane.showMessageDialog(null, message);
			MessageDialog.openInformation(new Shell(Display.getDefault()), "Infomation", message);
		
		}

		final GridBagConstraints gbc = new GridBagConstraints(0, 0, 1, 1, 1, 1,
				GridBagConstraints.NORTHWEST, GridBagConstraints.NONE,
				new Insets(0, 0, 0, 0), 0, 0);
		private Container panel;

		public String[] promptKeyboardInteractive(String destination,
				String name, String instruction, String[] prompt, boolean[] echo) {
			panel = new JPanel();
			panel.setLayout(new GridBagLayout());

			gbc.weightx = 1.0;
			gbc.gridwidth = GridBagConstraints.REMAINDER;
			gbc.gridx = 0;
			panel.add(new JLabel(instruction), gbc);
			gbc.gridy++;

			gbc.gridwidth = GridBagConstraints.RELATIVE;

			JTextField[] texts = new JTextField[prompt.length];
			for (int i = 0; i < prompt.length; i++) {
				gbc.fill = GridBagConstraints.NONE;
				gbc.gridx = 0;
				gbc.weightx = 1;
				panel.add(new JLabel(prompt[i]), gbc);

				gbc.gridx = 1;
				gbc.fill = GridBagConstraints.HORIZONTAL;
				gbc.weighty = 1;
				if (echo[i]) {
					texts[i] = new JTextField(20);
				} else {
					texts[i] = new JPasswordField(20);
				}
				panel.add(texts[i], gbc);
				gbc.gridy++;
			}

			if(prompt.length == 1 && prompt[0].trim().contains("Password:") ){
				String[] response = new String[1];
				response[0] =  getPassword();
				return response;
			}
			
			
			if (JOptionPane.showConfirmDialog(null, panel, destination + ": "
					+ name, JOptionPane.OK_CANCEL_OPTION,
					JOptionPane.QUESTION_MESSAGE) == JOptionPane.OK_OPTION) {
				String[] response = new String[prompt.length];
				for (int i = 0; i < prompt.length; i++) {
					response[i] = texts[i].getText();
				}
				return response;
			} else {
				return null; // cancel
			}
		}
	}

}
